<?php


namespace App\Models;


class Knowledge extends Model
{
    protected $table = 'knowledge';

    // ============= relations ==========
    public function tag()
    {
        return $this->belongsTo(Tag::class, 'tag_id');
    }

    public function audio()
    {
        return $this->belongsTo(Attachment::class, 'audio');
    }

    public function lesson()
    {
        return $this->belongsToMany(Lesson::class, 'knowledge_lesson');
    }

    // ============= field ==========
    public function setName($name)
    {
        $this->en_name = $name;
    }

    public function getName()
    {
        return $this->en_name;
    }

    public function setChinese($chinese)
    {
        $this->cn_name = $chinese;
    }

    public function getChinese()
    {
        return $this->cn_name;
    }

    public function setAudio($audio)
    {
        $this->audio = $audio;
    }

    public function getAudio()
    {
        return $this->audio;
    }

    public function setTagId($tag)
    {
        $this->tag_id = $tag;
    }

    public function getTagId()
    {
        return $this->tag_id;
    }


    public function setPartOfSpeech($partOfSpeech)
    {
        $this->part_of_speech = $partOfSpeech;
    }

    public function getPartOfSpeech()
    {
        return $this->part_of_speech;
    }

    public function setImages($images)
    {
        $this->images = json_encode($images);
    }

    public function getImages()
    {
        return json_decode($this->images, true) ?? [];
    }

    public function getCover()
    {
        $images = json_decode($this->images, true);
        $uri = null;
        if (is_array($images)) {
            foreach ($images as $image) {
                if (!empty($image['isCover'])) {
                    $uri = Attachment::where('id', $image['id'])->value('uri');
                    // @todo 处理图片
                    $uri = $uri . '?x-oss-process=style/word';
                }
            }
        }
        return $uri;
    }

    public function getImagesForTest($count = 3)
    {
        $images = json_decode($this->images, true);
        $tmp = [];
        if (is_array($images)) {
            foreach ($images as $image) {
                $uri = Attachment::where('id', $image['id'])->value('uri');
                // @todo 处理图片
                $tmp[] = $uri . '?x-oss-process=style/word';
            }
        }
        return array_slice($tmp, 0, $count);
    }

    public static function checkIsKnowledge($knowledgeId)
    {
        return static::where('id', $knowledgeId)->where('type', 0)->exists();
    }
}
